import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import '../../blocs/code.dart';
import '../../blocs/profile.dart';
import '../../util/app_util.dart';
import '../../blocs/cart.dart';
import '../../blocs/helper.dart';

class AccountAddressListScreen extends StatefulWidget {
  const AccountAddressListScreen({
    Key? key,
  }) : super(key: key);
  @override
  _AccountAddressListScreenState createState() => _AccountAddressListScreenState();
}

class _AccountAddressListScreenState extends State<AccountAddressListScreen> {
  @override
  late ProfileBloc lb_profile;
  late HelperBloc lb_helper;

  void initState() {
    super.initState();
    lb_profile = context.read<ProfileBloc>();
    lb_helper = context.read<HelperBloc>();
    WidgetsBinding.instance?.addPostFrameCallback((callback) async {
      await lb_profile.addrList();
    });
  }

  List<Widget> list = List<Widget>.empty(growable :true);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            child: Icon(
              Icons.chevron_left,
              color: AppColor.blackMain,
              size: 32,
            ),
          ),
        ),
        title: Text(
          AppText.text['account_addr_list'],
          style: TextStyle(color: AppColor.blackMain),
        ),
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              if ((AppSession.authortoken ?? '').isEmpty) {
              } else {
                AppSession.addrEdit = {};
                App.router.navigateTo(context, AppRoutes.accountAddr);
              }
            },
            child: Padding(
              padding: EdgeInsets.only(top: 14.h, right: 10.w),
              child: Text(
                '+ 添加新地址',
                style: TextStyle(color: AppColor.yellowText, fontSize: 14.sp),
              ),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Container(
          color: Colors.grey[50],
          margin: EdgeInsets.only(top: 20.h),
          child: Consumer<ProfileBloc>(
            builder: (context, _profile, child) => Builder(builder: (context) {
              return _addressList(context, _profile);
            }),
          ),
          // ((lb_profile?.addr_list ?? []).isNotEmpty)
          //     ?

          // : Container(),
        ),
      ),
    );
  }

  Widget _addressList(BuildContext context, ProfileBloc ib_profile) {
    list.clear();
    for (var lm_addr in ib_profile.addr_list) {
      list.add(GestureDetector(
        onTap: () async {},
        behavior: HitTestBehavior.opaque,
        child: _addressBlock(lm_addr),
      ));
    }
    if (list.isEmpty)
      return Center(
        child: Column(
          children: <Widget>[
            Text(AppText.text['account_addr_noaddr'] ?? ''),
          ],
        ),
      );
    else
      return Column(children: list);
  }

  Widget _addressBlock(Map<String, dynamic> iv_addr) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 18.w, vertical: 3.h),
      child: Card(
        child: Container(
          height: 130.h,
          width: ScreenUtil().screenWidth.toDouble(),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                children: <Widget>[
                  GestureDetector(
                    onTap: () async {
                      if (iv_addr['is_default'] != 1) {
                        var lv_param = iv_addr;
                        lv_param['is_default'] = 1;

                        var lm_result = await lb_profile.addrMaintain(lv_param);

                        if ((lm_result ?? {}).isNotEmpty) {
                          if ((lm_result['ev_error'] == 0) &&
                              ((lm_result['ev_result'] ?? {}).isNotEmpty)) {
                            AppSession.userAddr = lm_result['ev_result']['user_address'];
                            lb_helper.addrUpdate(AppSession.userAddr);
                            Map<String, dynamic> lm_cart_param = {
                              'uaid': lm_result['ev_result']['uaid']
                            };

                            if ((Provider.of<CartBloc>(context, listen: false).ticket)
                                .isNotEmpty) {
                              var lv_result = await Provider.of<CartBloc>(context, listen: false)
                                  .checkoutUpdate(lm_cart_param);
                            }
                          }
                        }

                        await lb_profile.addrList();
                      }
                    },
                    child: Container(
                      width: 70.w,
                      color: Colors.white,
                      child: Center(
                        child: (iv_addr['is_default'] == 1)
                            ? Icon(Icons.clear)
                            : Icon(Icons.clear),
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 30.h),
                    width: 200.w,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          iv_addr['consignee_name'] + '   ' + iv_addr['consignee_phone'],
                          style: TextStyle(fontSize: 13.sp, fontWeight: FontWeight.w600),
                        ),
                        Text(
                          iv_addr['addr'],
                          style: TextStyle(fontSize: 13.sp),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.only(right: 10.w),
                child: IconButton(
                  icon: Icon(
                    Icons.clear,
                    color: AppColor.yellowText,
                  ),
                  onPressed: () async {
                    AppSession.addrEdit = iv_addr;
                    App.router.navigateTo(context, AppRoutes.accountAddr);
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
